﻿
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Microsoft.Win32;
using MongoDB.Bson;
using MongoDB.Bson.Serialization;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Linq;

using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;


namespace component
{
   
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    /// 
    public partial class MainWindow : Window
    {
        public ExternalCommandData commandData;
        private  string message;
        private ElementSet elements;
        
        
        public MainWindow(ExternalCommandData commandData)

        {
            ExactFamily(commandData);
           this.commandData = commandData;
            InitializeComponent();
        }
        Family family = null;
        private Result ExactFamily(ExternalCommandData commandData)
        {
            Document doc = commandData.Application.ActiveUIDocument.Document;

            string s = @"D:\混凝土梁-矩形砼梁-有标记.rfa";
            Transaction tran = new Transaction(doc);
            tran.Start("载入族");
            bool b = doc.LoadFamily(s, out family);
            tran.Commit();
            //if (b) { TaskDialog.Show("11", "加载成功"); }
            Element element = family as Element;
            Transaction trandelete = new Transaction(doc);//创建事物
            trandelete.Start("删除族");//开启事物                 
            trandelete.Commit();//关闭事物
           
            
            try
            {
                // 获得族管理器
                FamilyManager familyMgr = doc.FamilyManager;
                FamilyType currType = familyMgr.CurrentType;
                if (currType != null)
                {   // 当前族类型可能为空，故需进行空检查
                    FamilyParameterSet familyParamSet = familyMgr.Parameters;
                    ISet<ElementId> familySymbolIds = family.GetFamilySymbolIds();
                    string info = "{ ";
                    foreach (ElementId id in familySymbolIds)
                    {
                        
                        FamilySymbol familySymbol = family.Document.GetElement(id) as FamilySymbol;
                        info += "\"Name\": " +  "\""+ familySymbol.Name +"\"" +",";
                        
                        foreach (FamilyParameter param in familyParamSet)
                        {

                            if (param.Definition.ParameterType == ParameterType.Length)
                            {
                                double dbl1 = currType.AsDouble(param).Value;
                                double d = UnitUtils.Convert(dbl1, DisplayUnitType.DUT_DECIMAL_FEET, DisplayUnitType.DUT_METERS);
                                info += "\"" + param.Definition.Name +"\""+ ":" + "\"" +  d + "\"" + ",";
                            }
                            else
                            {
                                info += "\"" + param.Definition.Name + "\"" + ":" + "\"" + " - " + "\"" + ",";
                            }
                        }
                       
                        
                       

                      
                        BsonDocument document = BsonSerializer.Deserialize<BsonDocument>(info);

                        //弹窗展示json格式参数信息
                        
                        string connStr = "mongodb://127.0.0.1:27017";

                        //2.创建连接MongoClient实例实际上代表了一个到数据库的连接池，即使有多个线程，也只需要一个MongoClient类的实例
                        var client = new MongoClient(connStr);

                        //3.使用client的GetDatabase方法获取数据库，即使该数据库不存在，也会自动创建；
                        IMongoDatabase db = client.GetDatabase("test");
                        //4.获取数据集 collection；BsonDocument是在数据没有预先定义好的情况下使用的。
                        IMongoCollection<BsonDocument> collection = db.GetCollection<BsonDocument>("family");
                        //5.插入一条数据;
                        collection.InsertOne(document);

                    }
                    info += "\"a\": \"a\"}";
                    StreamWriter sw = new StreamWriter("E:\\11.txt", false);
                    sw.WriteLine(info);
                    sw.Close();
                    TaskDialog.Show("Result", "保存成功");
                    MessageBox.Show(info, "信息");
                }
               
            }
            catch (Exception ex)
            {
                Console.WriteLine("Revit", ex.Message);
            }

            return Result.Succeeded;
        }
        //下载
        //public void downLoad(object sender, RoutedEventArgs e, string filename)
        //{
        //    socketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建一个socket的对象
        //    IPAddress ip = IPAddress.Parse(serverIp);//获取服务器IP地址
        //    IPEndPoint point = new IPEndPoint(ip, serverPort);//获取端口
        //    try
        //    {
        //        socketClient.Connect(point);//链接服务器IP与端口
        //        Console.WriteLine("连接服务器中.....");

        //    }
        //    catch (Exception)
        //    {
        //        Console.WriteLine("与服务器链接失败！");
        //        return;
        //    }
        //    Console.WriteLine("与服务器链接成功！");
        //    //String filename = "标高_卫生间.rfa";
        //    byte[] filename_Byte = System.Text.Encoding.UTF8.GetBytes(filename);//文件名的数组
        //    byte[] filenameLength = new byte[1];//文件名长度的数组
        //    filenameLength[0] = (byte)filename_Byte.Length;
        //    socketClient.Send(filenameLength);//发送文件名长度
        //    socketClient.Send(filename_Byte);//发送文件名
        //    Console.Write("发送请求完毕");
        //    byte[] fileLength = new byte[socketClient.ReceiveBufferSize];//接受文件长度的数组
        //    socketClient.Receive(fileLength);//接受文件长度
        //    long filelong = BytesToLong(fileLength);
        //    System.Windows.Forms.FolderBrowserDialog dialog = new System.Windows.Forms.FolderBrowserDialog();
        //    dialog.Description = "请选择文件路径";
        //    Console.WriteLine("执行完毕");
        //    dialog.ShowDialog();
        //    string file_path = dialog.SelectedPath;
        //    //得到选择文件的路径
        //    //string spath = @"E:\存放";//制定存储路径
        //    savePath = System.IO.Path.Combine(file_path, filename);//获取存储路径及文件名
        //    FileStream fileStream1 = new FileStream(savePath, FileMode.Create, FileAccess.Write);
        //    int rec = 0;//每次转换的长度
        //    long recFileLength = 0;//接受的文件长度
        //    byte[] buffer = new byte[1024];//接受文件的数组
        //    while (recFileLength < filelong)
        //    {
        //        rec = socketClient.Receive(buffer);
        //        fileStream1.Write(buffer, 0, rec);
        //        fileStream1.Flush();
        //        recFileLength++;
        //    }
        //    Execute(commandData, ref message1, elements);
        //    fileStream1.Close();
        //}
        //public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        //{
        //    UIApplication uiapp = commandData.Application;
        //    UIDocument uidoc = uiapp.ActiveUIDocument;
        //    Document familyDoc = uidoc.Document;
        //    Family family = null;
        //    using (Transaction tran = new Transaction(familyDoc, "11"))
        //    {
        //        tran.Start();
        //        familyDoc.LoadFamily(savePath, out family);

        //        tran.Commit();
        //    }
        //    if (family != null)
        //    {
        //        var symbol = familyDoc.GetElement(family.GetFamilySymbolIds().FirstOrDefault()) as FamilySymbol;
        //        uidoc.PromptForFamilyInstancePlacement(symbol);
        //    }
        //    return Result.Succeeded;
        //}
        ////将字符数组转换成Long型的方法
        //static long BytesToLong(byte[] bytes)
        //{
        //    return BitConverter.ToInt64(bytes, 0);
        //}
        //转换界面
        private void personalSpace(object sender, RoutedEventArgs e)
        {
            initialNavagation.Visibility = System.Windows.Visibility.Collapsed;
            //NavagationPage2 navagationPage2 = new NavagationPage2();
            Navagetion_Page_Change.Content = new System.Windows.Controls.Frame()

            {
                Content = navagationPage2
            };
        }
        private void navagetion_allComponents(object sender, RoutedEventArgs e)
        {
            initialNavagation.Visibility = System.Windows.Visibility.Collapsed;
            //NavagationPage1 navagationPage1 = new NavagationPage1();
            Navagetion_Page_Change.Content = new System.Windows.Controls.Frame()
            {
                Content = navagationPage1
            };
        }
        
        public string message1;
        public string savePath;
        public static string serverIp = "127.0.0.1";//设置服务端IP
        public static int serverPort = 8888;//服务端端口
        public static Socket socketClient;//定义socket
        private NavagationPage1 navagationPage1 = new NavagationPage1();
        private NavagationPage2 navagationPage2 = new NavagationPage2();
    }
}
